import React, { PureComponent } from 'react';
import { Card, Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import router from 'umi/router';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { connect } from 'dva';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import { filterAuth } from '@/support/common';
import * as G from '@/utils/common';

const mapStateToProps = (state: any) => ({
  basedata: state.basedata,
  digitalKeyModelsGroup: state.digitalKeyModelsGroup,
  loading: state.loading.effects['digitalKeyModelsGroup/getFetchPage'],
  menu: state.menu,
});
class DigitalKeyModelsGroup extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {}, //查询条件
      brandOptions: [],
      seriesOptions: [], // 车系的下拉列表
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res) =>
        this.setState({ brandOptions: res?.data }, () => {
          this.handleFlushPage();
        }),
    });
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'digitalKeyModelsGroup/initData',
    });
  }
  //页面刷新
  handleFlushPage() {
    const { dispatch } = this.props;
    const { formValues, brandOptions } = this.state;
    const params = {
      ...formValues,
    };
    if (!params.brandCode) params.brandCode = brandOptions.map((o) => o.brandCode)?.join(',');
    dispatch({
      type: 'digitalKeyModelsGroup/getFetchPage',
      payload: { url: '/bluetooth/key/group/list', ...params },
    });
  }

  // 按品牌选车系
  onBrandSelect = (value) => {
    const { dispatch } = this.props;
    this.setState({ seriesOptions: [] });
    this.search.current?.setFieldsValue({ seriesCode: undefined });
    if (!value) {
      return;
    }
    dispatch({
      type: 'basedata/seriesList',
      payload: { brandId: value },
      callback: (response) => {
        if (response) {
          this.setState({
            seriesOptions: response.filter((item) => item.code !== ''),
          });
        }
      },
    });
  };
  handleAdd = () => {
    const path = {
      pathname: '/bluetoothCloseControl/digitalKeyModelsGroup/digitalKeyModelsGroupAdd',
    };
    router.push(path);
  };
  //编辑
  handleEdit(record) {
    sessionStorage.setItem('digitalKeyGroupData', JSON.stringify(record));
    const path = {
      pathname: '/bluetoothCloseControl/digitalKeyModelsGroup/digitalKeyModelsGroupEdit',
    };
    router.push(path);
  }
  handleDetail = ({ code, brandCode, seriesCode }) => {
    console.log(code);
    const { dispatch } = this.props;
    dispatch({
      type: 'basedata/seriesList',
      payload: { brandId: brandCode },
      callback: (response) => {
        if (response) {
          router.push({
            pathname: '/bluetoothCloseControl/digitalKeyModelsGroup/digitalKeyModelsGroupDetail',
            query: {
              code,
              brandCode,
              seriesCode,
              seriesOptions: response.filter((item) => item.code !== ''),
            },
          });
        }
      },
    });
  };
  handleRemove = (sid) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'digitalKeyModelsGroup/postObjWithRes',
      payload: { url: '/bluetooth/key/group/delete', sid },
      callback: (response) => {
        response.statusCode === '0'
          ? message.success('删除成功')
          : message.error(response.statusMessage);
        this.handleFlushPage();
      },
    });
  };
  handleFieldsValue = (fields) => {
    const { brandOptions } = this.state;
    if (G.isEmptyOrNil(fields['brandCode'])) {
      fields['brandCode'] = brandOptions.map((o) => o.brandCode)?.join(',');
    }
    return { ...fields };
  };
  render() {
    const {
      digitalKeyModelsGroup: {
        pageData: { rows, pagination },
      },
      loading,
      dispatch,
      location: { pathname = '/' },
      menu: { permissions },
    } = this.props;
    const { formValues, brandOptions, seriesOptions } = this.state;
    const isAddAuth = filterAuth('digitalKeyModelsGroup-add', permissions, pathname);
    // //通过车系code转换车系name
    // const getSeriseName = function (code) {
    //   let name = code;
    //   seriesOptions.map((item) => {
    //     if (item.code === code) {
    //       name = item.name;
    //     }
    //   });
    //   return name;
    // };
    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        key: 'brandCode',
        keyValue: ['brandCode', 'brandName'],
        selectOptions: brandOptions,
        onChange: (e: any) => {
          this.onBrandSelect(e);
        },
      },
      {
        title: '车系',
        type: 'select',
        key: 'seriesCode',
        keyValue: ['code', 'name'],
        selectOptions: seriesOptions,
      },
      {
        title: '钥匙车型组编码',
        type: 'input',
        key: 'code',
      },
      {
        title: '钥匙车型组名称',
        type: 'input',
        key: 'name',
      },
    ];
    const columns = [
      {
        title: '品牌',
        dataIndex: 'brandName',
      },
      {
        title: '车系',
        dataIndex: 'seriesName',
        render: (text) => (
          <Ellipsis length={10} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '钥匙车型组编码',
        dataIndex: 'code',
        render: (text) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '钥匙车型组名称',
        dataIndex: 'name',
        render: (text) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        render: (text) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 180,
        fixed: 'right',
        render: (text, record) => {
          const btns = [
            {
              title: '查看',
              key: 'detail',
              auth: 'digitalKeyModelsGroupDetail',
              onConfirm: () => this.handleDetail(record),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'digitalKeyModelsGroup-edit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'delete',
              message: '确认删除？',
              auth: 'digitalKeyModelsGroup-del',
              Popconfirm: true,
              onConfirm: () => this.handleRemove(record.sid),
            },
          ];
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true, //每页显示多少条
      showQuickJumper: true, //输数字快捷跳转
      ...pagination,
      showTotal: () => {
        return <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>;
      }, //展示页码信息栏
    };

    // 页面需要的一些数据信息
    const tableProps = {
      columns: columns, //列表标题信息
      dataSource: rows, //要渲染的数据信息
      loading: loading, //设置加载的lodalind
      rowKey: (record) => {
        return record.sid;
      }, //接收每一行信息参数,设置每一行的key
      pagination: paginationProps, //分页信息,如果没有分页则为false
      //scroll: { x: '120%' },
    };

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(search) => (this.search = search)}
            searchItems={searchItems}
            fetchParams={{
              type: 'digitalKeyModelsGroup/getFetchPage',
              url: '/bluetooth/key/group/list',
            }}
            handleFieldsValue={this.handleFieldsValue}
            dispatch={dispatch}
            saveFormValues={(val) => this.setState({ formValues: Object.assign(formValues, val) })}
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {isAddAuth && (
            <div className="my_newItem">
              <Button icon={<PlusOutlined />} type="primary" size="small" onClick={this.handleAdd}>
                新增
              </Button>
            </div>
          )}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            dispatch={dispatch}
            fetchParams={{
              type: 'digitalKeyModelsGroup/getFetchPage',
              url: '/bluetooth/key/group/list',
              extraArgs: {
                brandCode: !formValues.brandCode
                  ? brandOptions.map((o: { brandCode: any }) => o.brandCode)?.join(',')
                  : formValues.brandCode,
              },
            }}
            formValues={formValues}
            currentName="curPage"
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(DigitalKeyModelsGroup);
